package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMappr;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMappr dishFlavorMappr;

    @Autowired
    private SetmealDishMapper setmealDishMapper;


    /**
     * 修改菜品数据回显
     *
     * @param id
     */
    @Override
    public DishVO getById(Long id) {
        // 获取菜品基本数据
        Dish dish = dishMapper.selectById(id);
        // 获取菜品口味列表
        List<DishFlavor> dishFlavorList = dishFlavorMappr.selectByDishId(id);
        // 构造dishvo对象并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional// 开启事务【涉及到两张表的操作】
    public void adddDish(DishDTO dishDTO) {
        //     改造菜品基本信息数据
        Dish dish = new Dish();
        // 拷贝属性值
        BeanUtils.copyProperties(dishDTO, dish);
        //     存入dish表
        dishMapper.insert(dish);
        //     改造菜品口味列表数据
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        // 判断有没有dishflavor
        if(dishFlavors == null && dishFlavors.size() <= 0){
            return ;
        }
        // 关联菜品id
        dishFlavors.forEach(flavor -> {
            flavor.setDishId(
                    dish.getId()//暂时数据
            );
        });
        //     存入dish.flavor
        dishFlavorMappr.insertBatch(dishFlavors);
    }

    /**
     * 菜品列表分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        // 设置分页参数
        PageHelper.startPage(
                dishPageQueryDTO.getPage(),
                dishPageQueryDTO.getPageSize()
        );
        // 调用mapper
        Page<DishVO> page = dishMapper.list(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional// 开启事务
    public void delete(List<Long> ids) {
        //     判断菜品是否起售，处于起售中的菜品不允许删除
        ids.forEach(id -> {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //     判断菜品是否被套餐关联，关联不允许删除
        Integer count = setmealDishMapper.countByDishIds(ids);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        //     删除菜品基本信息
        dishMapper.deleteBatch(ids);
        //     删除菜品口味列表信息
        dishFlavorMappr.deleteBatch(ids);
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional// 开启事务
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //     修改菜品的基本信息
        dishMapper.update(dish);

        //     修改口味列表信息
        //     口味数据可能删除，增加，或者修改，使用直接全部删除，再添加新数据
        dishFlavorMappr.deletebyDishId(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            // 关联菜品id
            flavors.forEach(flavor -> {
                flavor.setDishId(
                        dish.getId()//暂时数据
                );
            });
            // 批量插入
            dishFlavorMappr.insertBatch(flavors);
        }

    }

    /**
     * 根据菜品种类查询菜品列表
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> getDishesByCategoryId(Integer categoryId) {

        return dishMapper.selectByCategoryId(categoryId);
    }

    /**
     * 更改菜品状态
     *
     * @param status
     * @param id
     */
    @Override
    public void changeStatus(Integer status, Long id) {
        Dish dish = Dish.builder().id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
    }

    /**
     * 查询菜品数据并伴随口味
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {
        final List<DishVO> dishVOList = new ArrayList<>();
        // 补充查询数据
        DishDTO dishDTO = new DishDTO();
        dishDTO.setCategoryId(categoryId);
        dishDTO.setStatus(StatusConstant.ENABLE);
        // 查询出符合的菜品列表
        final List<Dish> dishList = dishMapper.listAll(dishDTO);
        // 更具菜品列表的id查询dish_flavor数据
        dishList.forEach(dish -> {
            final DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            dishVO.setFlavors(
                    dishFlavorMappr.selectByDishId(dish.getId())
            );
            dishVOList.add(dishVO);
        });
        // 返回数据
        return dishVOList;
    }
}
